const db = require('../utils/db')
const jwt = require('jsonwebtoken')
const config = require('../config')
const bcrypt = require('bcryptjs')

// 手机号&验证码
var phoneAndCode = []

// 随机生成6位验证码
function randCode(){
  return parseInt(Math.random()*(999999-100000)+100000)
}

// 随机生成10位字符
function randStr(n=10){
  const t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678"
  const len = t.length
  let str = ''
  for(let i=0; i<n; i++){
    str += t.charAt(Math.floor(Math.random()*len)) 
  }
  return str
}

// 验证手机号和验证码
function verifyPhoneAndCode(phone, code){
  for(let item of phoneAndCode){
    if(item.phone==phone && item.code==code && item.create<=(Date.now()+60000)){
      phoneAndCode = phoneAndCode.filter(item=>item.phone != phone)
      return true
    }
  }
  return false
}

// 验证码: 1分钟内有效
exports.sendCode = (req, res)=>{
  const yzm = randCode()
  phoneAndCode.push({
    phone: req.body.phone,
    code: yzm,
    create: Date.now()
  })
  res.send({code: 0, msg: '发送验证码成功', yzm})
}

// 登录
exports.login = (req, res)=>{
  // 验证手机号和收到的验证码
  if(req.body.type=='code'){
    if(!verifyPhoneAndCode(req.body.phone, req.body.code)) 
      return res.er('手机号或验证码改变')
  }
  let sql = `select * from users where phone=${req.body.phone}`
  db.query(sql, (err, result1)=>{
    if(err) return res.er(err)
    // 第一次登录，注册账号
    if(result1.length==0 && req.body.type=='code'){
      // 自动生成唯一账号
      sql = 'select username from users'
      db.query(sql,(err, result2)=>{
        if(err) return res.er(err)
        let username = randStr()
        let isUnique = false
        while(!isUnique){
          let hasSame = result2.some(x=>username==x.username)
          if(hasSame){
            username = randStr()
          }else{
            isUnique = true
          }
        }
        // 账号注册
        sql = 'insert into users set ?'
        db.query(sql,{
          username,
          phone: req.body.phone,
          createAt: Date.now()
        }, (err, result3)=>{
          if(err) return res.er(err)
          if(result3.affectedRows != 1) return res.er('登录失败')
          const token = jwt.sign({id:result3.insertId, username}, config.jwtKey, {expiresIn:'10h'})
          res.send({code:0, msg:'账号注册成功', token})
        })
      })
    }
    // 第一次登录，选择了密码方式
    else if(result1.length==0 && req.body.type=='password'){
      return res.er('登录失败，第一次登录，请选择验证码方式')
    }
    // 不是第一次登录
    else{
      // 密码登录
      if(req.body.type=='password'){
        if(!result1[0].password) return res.er('密码未设置，请选择验证码登录')
        const isSame = bcrypt.compareSync(req.body.password,result1[0].password)
        if(!isSame) return res.er('密码错误')
        const token = jwt.sign({id:result1[0].id, username:result1[0].username}, config.jwtKey, {expiresIn:'10h'})
        res.send({code:0, msg:'密码登录成功', token})
      }
      // 验证码登录
      else if(req.body.type=='code'){
        const token = jwt.sign({id:result1[0].id, username:result1[0].username}, config.jwtKey, {expiresIn:'10h'})
        res.send({code:0, msg:'验证码登录成功', token})
      }
    }
  })
}

// 获取用户信息
exports.getUserinfo = (req, res)=>{
  db.query('select * from users where id=?',req.user.id,
    (err, result)=>{
      if(err) return res.er(err)
      if(result.length != 1)  res.er('获取用户信息失败')
      res.send({code:0, msg:'获取用户信息成功', dt: {...result[0],password:''}})
    })
}

// 更新头像
exports.upadateAvatar = (req, res)=>{
  const sql = `update users set avatarUrl=? where id=?`
  db.query(sql, [req.file.path,req.user.id], (err, results)=>{
    if(err) return res.er(err)
    if(results.affectedRows != 1)  res.er('更新用户头像失败')
    res.send({code:0, msg:'更新用户头像成功', dt: req.file.path})
  })
}

// 修改昵称
exports.updateNickname = (req, res)=>{
  const sql = `update users set nickname='${req.body.nickname}' where id=${req.user.id}`
  db.query(sql,(err, results)=>{
    if(err) return res.er(err)
    if(results.affectedRows != 1)  res.er('更新用户昵称失败')
    res.send({code:0, msg:'更新用户昵称成功', dt: req.body.nickname})
  })
}

// 修改性别
exports.updateGender = (req, res)=>{
  const sql = `update users set gender=? where id=?`
  db.query(sql, [req.body.gender,req.user.id], (err, results)=>{
    if(err) return res.er(err)
    if(results.affectedRows != 1)  res.er('更新性别失败')
    res.send({code:0, msg:'更新性别成功', dt: req.body.gender})
  })
}

// 修改生日
exports.updateBirthday = (req, res)=>{
  const sql = `update users set birthday=? where id=?`
  db.query(sql, [req.body.birthday,req.user.id], (err, results)=>{
    if(err) return res.er(err)
    if(results.affectedRows != 1)  res.er('更新用户生日失败')
    res.send({code:0, msg:'更新用户生日成功', dt: req.body.birthday})
  })
}

// 修改所在地
exports.updateAddress = (req, res)=>{
  const sql = `update users set address=? where id=?`
  db.query(sql, [req.body.address,req.user.id], (err, results)=>{
    if(err) return res.er(err)
    if(results.affectedRows != 1)  res.er('更新用户所在地失败')
    res.send({code:0, msg:'更新用户所在地成功', dt: req.body.address})
  })
}

// 修改学校
exports.updateSchool = (req, res)=>{
  const sql = `update users set school=? where id=?`
  db.query(sql, [req.body.school,req.user.id], (err, results)=>{
    if(err) return res.er(err)
    if(results.affectedRows != 1)  res.er('更新用户学校失败')
    res.send({code:0, msg:'更新用户学校成功', dt: req.body.school})
  })
}

// 修改个人介绍
exports.updateSignature = (req, res)=>{
  const sql = `update users set signature=? where id=?`
  db.query(sql, [req.body.signature,req.user.id], (err, results)=>{
    if(err) return res.er(err)
    if(results.affectedRows != 1)  res.er('更新用户个人介绍失败')
    res.send({code:0, msg:'更新用户个人介绍成功', dt: req.body.signature})
  })
}
 
// 修改背景图
exports.updateBackground = (req, res)=>{
  const sql = `update users set backgroundUrl=? where id=?`
  db.query(sql, [req.file.path,req.user.id], (err, results)=>{
    if(err) return res.er(err)
    if(results.affectedRows != 1)  res.er('更新背景失败')
    res.send({code:0, msg:'更新背景成功', dt: req.file.path})
  })
}

// 身份认证
exports.verifyID = (req, res)=>{
  if(!verifyPhoneAndCode(req.body.phone, req.body.code)) return res.er('身份验证失败')
  res.send({code:0, msg:'身份验证成功'})
}

// 设置密码
exports.updatePassword = (req, res)=>{
  const pwd = bcrypt.hashSync(req.body.password,10)
  const sql = `update users set password=? where id=? and phone=?`
  const values = [pwd, req.user.id, req.body.phone]
  db.query(sql, values, (err, results)=>{
    if(err) return res.er(err)
    if(results.affectedRows != 1)  res.er('更新密码失败')
    res.send({code:0, msg:'更新密码成功'})
  })
}

// 更换手机号
exports.updatePhone = (req, res)=>{
  if(!verifyPhoneAndCode(req.body.phone, req.body.code)) return res.er('更换手机号失败1')
  const sql = `update users set phone=? where id=?`
  const values = [req.body.phone, req.user.id]
  db.query(sql, values, (err, results)=>{
    if(err) return res.er(err)
    if(results.affectedRows != 1)  res.er('更换手机号失败2')
    res.send({code:0, msg:'更换手机号成功', dt:req.body.phone})
  })
}
